/**
 * Project: push-center-web-home
 * 
 * File Created at 2014年10月10日
 * 
 * Copyright 2012 Greenline.com Corporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Greenline Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Greenline.com.
 */
package com.greenline.push.home.controllers.appchannel;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.greenline.guser.annotation.GuserResource;
import com.greenline.guser.partner.dto.PartnerDTO;
import com.greenline.guser.partner.service.AuthoPartnerService;
import com.greenline.push.common.json.BaseJson;
import com.greenline.push.common.json.GridJsonData;
import com.greenline.push.common.utils.StringUtil;
import com.greenline.push.core.pushcenter.AppChannelManager;
import com.greenline.push.dal.base.PageQuery;
import com.greenline.push.dal.pushcenter.dataobject.AppChannelDO;
import com.greenline.push.dal.query.AppChannelQuery;
import com.greenline.push.services.RefreshConfigService;

/**
 * @Type AppChannelController
 * @Desc
 * @author zhaoli
 * @date 2014年10月10日
 * @Version V1.0
 */
@Controller
@RequestMapping(value = "/channel")
public class AppChannelController {

    @Resource
    private AppChannelManager appChannelManager;
    @Autowired
    private AuthoPartnerService authoPartnerService;
    @Value("${appserver.domainid}")
    private String domainId;

    @Resource
    private RefreshConfigService refreshService;

    private final Log logger = LogFactory.getLog(AppChannelController.class);

    @GuserResource("渠道配置列表")
    @RequestMapping(value = "/query", method = RequestMethod.GET)
    public String queryRecord(ModelMap model) {
        return "appchannel/appchannel_list";
    }

    @GuserResource("渠道配置列表")
    @RequestMapping("/query.json")
    @ResponseBody
    public GridJsonData<AppChannelDO> listRecord(AppChannelQuery query,
            @RequestParam(value = "page", defaultValue = "1", required = false) String pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "10", required = false) String pageSize) {
        query.setPageIndex(Integer.parseInt(pageIndex));
        query.setPageSize(Integer.parseInt(pageSize));
        GridJsonData<AppChannelDO> ret = new GridJsonData<AppChannelDO>();
        ret.setQuery(appChannelManager.listByQuery(query));
        return ret;
    }

    @GuserResource("渠道配置添加")
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String addInit(ModelMap model) {
        return "appchannel/appchannel_add";
    }

    @GuserResource("渠道配置添加")
    @RequestMapping(value = "/add.json", method = RequestMethod.POST)
    public @ResponseBody
    BaseJson add(ModelMap model, @ModelAttribute("template") AppChannelDO channel) {
        BaseJson json = new BaseJson();
        try {
            if (StringUtil.hasEmpty(channel.getAppId(), channel.getAppChannel(), channel.getExtAppId(), channel.getName())) {
                json.setHasError(true);
                json.setMessage("提交出错,请检查空值");
                return json;
            }
            if (appChannelManager.insert(channel) > 0) {
                json.setMessage("提交成功！");
            } else {
                json.setHasError(true);
                json.setMessage("提交出错");
            }
        } catch (Exception e) {
            json.setHasError(true);
            json.setMessage("提交出错");
            logger.error(json.getMessage(), e);
        }
        return json;
    }

    @GuserResource("渠道配置修改")
    @RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
    public String updateInit(ModelMap model, @PathVariable Long id) {
        AppChannelDO object = appChannelManager.getAppChannelById(id);
        model.put("channel", object);
        return "appchannel/appchannel_update";
    }

    @GuserResource("渠道配置修改")
    @RequestMapping(value = "/update.json", method = RequestMethod.POST)
    public @ResponseBody
    BaseJson update(ModelMap model, @ModelAttribute("channel") AppChannelDO channel) {
        BaseJson json = new BaseJson();
        try {
            if (appChannelManager.update(channel)) {
                json.setMessage("提交成功！");
            } else {
                json.setHasError(true);
                json.setMessage("提交出错");
            }
        } catch (Exception e) {
            json.setHasError(true);
            json.setMessage("提交出错");
            logger.error(json.getMessage(), e);
        }
        return json;
    }

    @GuserResource("渠道配置删除")
    @RequestMapping(value = "/delete.json", method = RequestMethod.POST)
    public @ResponseBody
    BaseJson delete(ModelMap model, @ModelAttribute("id") Long id) {
        BaseJson json = new BaseJson();
        try {
            if (appChannelManager.delete(id)) {
                json.setMessage("删除成功！");
            } else {
                json.setHasError(true);
                json.setMessage("删除出错");
            }
        } catch (Exception e) {
            json.setHasError(true);
            json.setMessage("删除出错");
            logger.error(json.getMessage(), e);
        }
        return json;
    }

    @GuserResource("渠道配置列表")
    @RequestMapping(value = "/listall", method = RequestMethod.GET)
    public String listallpartner(ModelMap model) {
        return "appchannel/listall";
    }

    @GuserResource("获取所有渠道 -db")
    @RequestMapping(value = "/listall-appid", method = RequestMethod.GET)
    public String listallappid(ModelMap model) {
        return "apptemplate/listall-appid";
    }

    @GuserResource("appchannel从guser获取")
    @RequestMapping(value = "/list-all.json")
    public @ResponseBody
    GridJsonData<PartnerDTO> listAll(ModelMap model, @RequestParam(value = "page", defaultValue = "1", required = false) String pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "10", required = false) String pageSize) {
        List<PartnerDTO> partnerList = new ArrayList<PartnerDTO>();
        int index = Integer.parseInt(pageIndex);
        int size = Integer.parseInt(pageSize);
        GridJsonData<PartnerDTO> ret = new GridJsonData<PartnerDTO>();
        List<PartnerDTO> retursnList = authoPartnerService.listPartnerByDomain(Long.valueOf(domainId));
        if (retursnList != null) {
            for (int i = (index - 1) * size; (i < (index - 1) * size + size) && i < retursnList.size(); i++) {
                partnerList.add(retursnList.get(i));
            }
        }
        PageQuery<PartnerDTO> query = new PageQuery<PartnerDTO>();
        query.setDataList(partnerList);
        query.setTotalRecord(retursnList.size());
        query.setPageIndex(index);
        query.setPageSize(size);
        ret.setQuery(query);
        return ret;
    }

    @RequestMapping(value = "/refresh.json")
    public @ResponseBody
    BaseJson refresh(ModelMap model) {
        BaseJson json = new BaseJson();
        try {
            if (refreshService.refreshAppChannelCache()) {
                json.setMessage("提交成功！");
            } else {
                json.setHasError(true);
                json.setMessage("提交出错");
            }
        } catch (Exception e) {
            json.setHasError(true);
            json.setMessage("提交出错");
            logger.error(json.getMessage(), e);
        }
        return json;
    }
}
